package com.suyin.ximoon.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suyin.ximoon.annotation.SystemLog;
import com.suyin.ximoon.controller.base.BaseController;
import com.suyin.ximoon.exception.ServiceException;
import com.suyin.ximoon.model.LyButtom;
import com.suyin.ximoon.model.LyResUser;
import com.suyin.ximoon.model.LyResources;
import com.suyin.ximoon.model.LyUserRole;
import com.suyin.ximoon.plugin.mybatis.Criteria;
import com.suyin.ximoon.plugin.mybatis.OrderBy;
import com.suyin.ximoon.plugin.mybatis.Restriction;
import com.suyin.ximoon.service.LyButtomService;
import com.suyin.ximoon.service.LyResUserService;
import com.suyin.ximoon.service.LyResourcesService;
import com.suyin.ximoon.service.LyUserRoleService;
import com.suyin.ximoon.util.Common;
import com.suyin.ximoon.util.JsonUtils;
import com.suyin.ximoon.util.Params;
import com.suyin.ximoon.util.Tools;
import com.suyin.ximoon.util.TreeObject;
import com.suyin.ximoon.util.TreeUtil;


/**
 * 
 * @author lanyuan 2014-11-19
 * @Email: mmm333zzz520@163.com
 * @version 3.0v
 */
@Controller
@RequestMapping("/resources/")
public class ResourcesController extends BaseController {
	@Resource
	private LyResourcesService lySesourcesService;
	@Resource
	private  LyUserRoleService lyUserRoleService;
	@Resource
	private  LyResUserService lyResUserService;
	
	@Resource
	private  LyButtomService lyButtomService;
	/**
	 * @param model
	 *            存放返回界面的model
	 * @return
	 * @throws ServiceException 
	 */
	@ResponseBody
	@RequestMapping("treelists")
	public HashMap<String,Object> findByPage(Model model,String name) throws ServiceException {
		Criteria c = new Criteria(); 
		 if (Tools.notEmpty(name))
         {
			 c .add(Restriction.like("name", name));
         }
		c.addOrderBy("level", OrderBy.OrderByType.ASC);
		List<LyResources> rlist =lySesourcesService.query(c);
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (LyResources  mp : rlist) {
			TreeObject ts = new TreeObject();
			ts.setId(mp.getId());
			ts.setDescription(mp.getDescription());
			ts.setIcon(mp.getIcon());
			ts.setIshide(mp.getIshide());
			ts.setLevel(mp.getLevel());
			ts.setName(mp.getName());
			ts.setParentId(mp.getParentId());
			ts.setParentName(mp.getParentName());
			ts.setResKey(mp.getResKey());
			ts.setResUrl(mp.getResUrl());
			ts.setType(mp.getType());
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
		HashMap<String,Object> resFormMap = new HashMap<String,Object>();
		resFormMap.put("treelists", ns);
		return resFormMap;
	}

	@ResponseBody
	@RequestMapping("reslists")
	public List<TreeObject> reslists(Model model) throws Exception {
		Criteria c = new Criteria(); 
		c.addOrderBy("level", OrderBy.OrderByType.ASC);
		List<LyResources> rlist =lySesourcesService.query(c);
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (LyResources  mp : rlist) {
			TreeObject ts = new TreeObject();
			ts.setId(mp.getId());
			ts.setDescription(mp.getDescription());
			ts.setIcon(mp.getIcon());
			ts.setIshide(mp.getIshide());
			ts.setLevel(mp.getLevel());
			ts.setName(mp.getName());
			ts.setParentId(mp.getParentId());
			ts.setParentName(mp.getParentName());
			ts.setResKey(mp.getResKey());
			ts.setResUrl(mp.getResUrl());
			ts.setType(mp.getType());
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, "　");
		return ns;
	}

	/**
	 * @param model
	 *            存放返回界面的model
	 * @return
	 */
	@RequestMapping("list")
	public String list(Model model) {
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/system/resources/list";
	}

	/**
	 * 跳转到修改界面
	 * 
	 * @param model
	 * @param resourcesId
	 *            修改菜单信息ID
	 * @return
	 * @throws ServiceException 
	 */
	@RequestMapping("editUI")
	public String editUI(Model model) throws ServiceException {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			Criteria c = new Criteria(); 
			c .add(Restriction.eq("id", id));
			model.addAttribute("resources", lySesourcesService.queryOne(c));
		}
		return Common.BACKGROUND_PATH + "/system/resources/edit";
	}

	/**
	 * 跳转到新增界面
	 * 
	 * @return
	 */
	@RequestMapping("addUI")
	public String addUI(Model model) {
		return Common.BACKGROUND_PATH + "/system/resources/add";
	}

	/**
	 * 权限分配页面
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2014-4-14
	 * @param model
	 * @return
	 * @throws ServiceException 
	 */
	@RequestMapping("permissions")
	public String permissions(Model model) throws ServiceException {
		Criteria c = new Criteria(); 
		c.addOrderBy("level", OrderBy.OrderByType.ASC);
		List<LyResources> rlist =lySesourcesService.query(c);
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (LyResources  mp : rlist) {
			TreeObject ts = new TreeObject();
			ts.setId(mp.getId());
			ts.setDescription(mp.getDescription());
			ts.setIcon(mp.getIcon());
			ts.setIshide(mp.getIshide());
			ts.setLevel(mp.getLevel());
			ts.setName(mp.getName());
			ts.setParentId(mp.getParentId());
			ts.setParentName(mp.getParentName());
			ts.setResKey(mp.getResKey());
			ts.setResUrl(mp.getResUrl());
			ts.setType(mp.getType());
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
		model.addAttribute("permissions", ns);
		return Common.BACKGROUND_PATH + "/system/resources/permissions";
	}

	/**
	 * 添加菜单
	 * 
	 * @param resources
	 * @return Map
	 * @throws Exception
	 */
	@RequestMapping("addEntity")
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="资源管理-新增资源")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity(LyResources resFormMap) throws Exception {
		if("2".equals(resFormMap.getType())){
			resFormMap.setDescription(Common.htmltoString(resFormMap.getDescription()+""));
		}
		Object o = resFormMap.getIshide();
		if(null==o){
			resFormMap.setIshide(0);;
		}
		lySesourcesService.insert(resFormMap);
		return "success";
	}

	/**
	 * 更新菜单
	 * 
	 * @param model
	 * @param Map
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="资源管理-修改资源")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(Model model,LyResources resFormMap) throws Exception {
		if("2".equals(resFormMap.getType())){
			resFormMap.setDescription(Common.htmltoString(resFormMap.getDescription()+""));
		}
		Object o = resFormMap.getIshide();
		if(null==o){
			resFormMap.setIshide(0);;
		}
		lySesourcesService.update(resFormMap);
		return "success";
	}

	/**
	 * 根据ID删除菜单
	 * 
	 * @param model
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("deleteEntity")
	@SystemLog(module="系统管理",methods="资源管理-删除资源")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity(Model model) throws Exception {
		String[] ids = getParaValues("ids");
		for (String id : ids) {
			Criteria c = new Criteria();
			c .add(Restriction.eq("id", id));
			lySesourcesService.delete(c);
		};
		return "success";
	}

	@RequestMapping("sortUpdate")
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String sortUpdate(Params params) throws Exception {
		List<String> ids = params.getId();
		List<String> es = params.getRowId();
		List<LyResources> maps = new ArrayList<LyResources>();
		for (int i = 0; i < ids.size(); i++) {
			LyResources map = new LyResources();
			map.setId(Integer.valueOf(ids.get(i)));
			map.setLevel(Integer.valueOf(es.get(i)));
			maps.add(map);
		}
		lySesourcesService.updateSortOrder(maps);
		return "success";
	}

	@ResponseBody
	@RequestMapping("findRes")
	public  String findUserRes(String userId,String roleId) {
		HashMap<String,Object> resFormMap = new HashMap<String,Object>();
		resFormMap.put("userId", userId);
		resFormMap.put("roleId", roleId);
		List<LyResources> rlist =lySesourcesService.findRes(resFormMap);
		return 	JsonUtils.listToJson(rlist);
	}
	@ResponseBody
	@RequestMapping("addUserRes")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理/组管理-修改权限")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addUserRes() throws Exception {
		String userId = "";
		String u = getPara("userId");
		String g = getPara("roleId");
		Criteria c = new Criteria();
		if (null != u && !Common.isEmpty(u.toString())) {
			userId = u.toString();
		} else if (null != g && !Common.isEmpty(g.toString())) {
			c .add(Restriction.eq("roleId", g.toString()));
			List<LyUserRole> gs = lyUserRoleService.query(c);
			for (LyUserRole ug : gs) {
				userId += ug.getUserId() + ",";
			}
		}
		userId = Common.trimComma(userId);
		if(Common.isEmpty(userId)){
			return "分配失败,该角色下没有用户!";
		}
		String[] users = userId.split(",");
		for (String uid : users) {
			c = new Criteria();
			c .add(Restriction.eq("userId",uid));
			lyResUserService.delete(c);
			String[] s = getParaValues("resId[]");
			List<LyResUser> resUserFormMaps = new ArrayList<LyResUser>();
			for (String rid : s) {
				LyResUser resUserFormMap = new LyResUser();
				resUserFormMap.setResId(Integer.valueOf(rid));
				resUserFormMap.setUserId(Integer.valueOf(uid));
				resUserFormMaps.add(resUserFormMap);
			
			}
			lyResUserService.insert(resUserFormMaps);
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("findByButtom")
	public List<LyButtom> findByButtom() throws ServiceException{
		Criteria c = new Criteria();
		return lyButtomService.query(c);
	}
	
	/**
	 * 验证菜单是否存在
	 * 
	 * @param name
	 * @return
	 * @throws ServiceException 
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name,String resKey) throws ServiceException {
		Criteria c = new Criteria();
		c .add(Restriction.eq("name", name));
		c .add(Restriction.eq("resKey", resKey));
		List<LyResources> r= lySesourcesService.query(c);
		if (r.size()==0) {
			return true;
		} else {
			return false;
		}
	}
}